package com.yitiao.simple.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.SneakyThrows;
import java.util.concurrent.TimeUnit;

/**
 * <h3>核心类: IdleStateHandler ,是netty 提供的处理空闲状态的处理器</h3>
 * long readerIdleTime : 表示多长时间没有读, 就会发送一个心跳检测包检测是否连接<br>
 * long writerIdleTime : 表示多长时间没有写, 就会发送一个心跳检测包检测是否连接<br>
 * long allIdleTime : 表示多长时间没有读写, 就会发送一个心跳检测包检测是否连接<br>
 */
public class BeatServer {

    @SneakyThrows
    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new IdleStateHandler(7,8,10, TimeUnit.SECONDS))
                                .addLast(new BeatServerHandler());
                    }
                });
        ChannelFuture future = server.bind(8801).sync();
        System.out.println("server is started...");

        future.channel().closeFuture().sync();

        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
